package com.example.demo.zabbix;

import com.example.demo.zabbix.request.BaseRequest;
import com.example.demo.zabbix.request.RequestHandler;
import com.example.demo.zabbix.request.builder.request.AuthRequestBuilder;
import com.example.demo.zabbix.request.builder.request.UnAuthRequestBuilder;
import com.example.demo.zabbix.request.builder.apiinfo.ApiinfoRequestBuilder;
import com.example.demo.zabbix.response.*;
import com.example.demo.zabbix.response.ApiinfoGetResponse;
import feign.Feign;
import feign.Logger;
import feign.gson.GsonEncoder;
import feign.slf4j.Slf4jLogger;

import java.time.Instant;

public class Zabbix {
    private static Api api = null;
    private String url = "api_jsonrpc.php";
    private String auth;

    public void init(String host) {
        init(host, Logger.Level.FULL);
    }

    public void init(String host, Logger.Level level) {
        api = Feign.builder().logger(new Slf4jLogger()).logLevel(level).requestInterceptor(new RequestHandler()).decoder(new ResponseDecoder()).encoder(new GsonEncoder()).target(Api.class, host);
        BaseResponse<String> baseResponse = this.call(new ApiinfoRequestBuilder().builder());
        System.out.printf("client version:%s->server version:%s", "4.0", new ApiinfoGetResponse(baseResponse).getVersion());
        System.out.println();
    }

    public void init(String host, String url, Logger.Level level) {
        this.url = url;
        this.init(host, level);
    }

    public void init(String host, String url) {
        this.url = url;
        this.init(host);
    }

    public String getAuth() {
        return auth;
    }

    public <T> BaseResponse<T> call(BaseRequest baseRequest) {
        return api.jsonrpc(baseRequest, url);
    }

    public String auth(String userName, String password) {
        BaseResponse<String> baseResponse = this.call(new AuthRequestBuilder(Instant.now().getEpochSecond()).setUserName(userName).setPassword(password).builder());
        auth = baseResponse.getResult();
        return baseResponse.getResult();
    }

    public Boolean unAuth(String auth) {
        BaseResponse<Boolean> baseResponse = this.call(new UnAuthRequestBuilder(Instant.now().getEpochSecond(), auth).builder());
        return baseResponse.getResult();
    }

    public Boolean unAuth() {
        return this.unAuth(auth);
    }
}
